//
//  TFPhotoBrowserVideoDisplayCell.m
//  Pods
//
//  Created by TFAppleWork-Summer on 2017/8/24.
//
//

#import "TFPhotoBrowserVideoDisplayCell.h"

//UI
#import "TFPhotoDownloadView.h"
#import "UIColor+TFPhoto.h"
#import "TFPhotoResourceHelper.h"

//工具类
#import "TFPhotoHandler.h"

//视频相关
#import <AVFoundation/AVFoundation.h>
#import "TFPhotoBrowserVideoPlayView.h"

static NSInteger kTFPhotoVideoDisplayDownloadFailViewTag = 100;
static NSInteger kTFPhotoVideoDisplayDownloadProgressViewTag = 101;

@interface TFPhotoBrowserVideoDisplayCell ()

@property (nonatomic, strong, readwrite) TFPhotoScrollView *photoScrollView;

@property (nonatomic, strong) TFPhotoBrowserVideoPlayView *videoPlayView;

@property (nonatomic, assign) PHImageRequestID iCloudRequestId;

@end

@implementation TFPhotoBrowserVideoDisplayCell

@synthesize photo = _photo;
@synthesize image = _image;
@synthesize photoScrollView = _photoScrollView;
@synthesize videoPlayView = _videoPlayView;
@synthesize indexPath = _indexPath;
@synthesize delegate = _delegate;
@synthesize isLoading = _isLoading;

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        _iCloudRequestId = 0;
        self.contentView.backgroundColor = [UIColor blackColor];
        [self.contentView addSubview:self.photoScrollView];
        [self.contentView addSubview:self.videoPlayView];
        //添加约束
        _photoScrollView.translatesAutoresizingMaskIntoConstraints = NO;
        _videoPlayView.translatesAutoresizingMaskIntoConstraints = NO;
        NSDictionary *viewDic = @{@"photoScrollView":self.photoScrollView,@"videoPlayView":self.videoPlayView};

        [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[photoScrollView]|" options:0 metrics:nil views:viewDic]];
        [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[photoScrollView]|" options:0 metrics:nil views:viewDic]];
        
        [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[videoPlayView]|" options:0 metrics:nil views:viewDic]];
        [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[videoPlayView]|" options:0 metrics:nil views:viewDic]];
        
        
    }
    return self;
}

- (UIImage *)image {
    return self.photoScrollView.image;
}

- (void)loadPhoto {
    if ([self.delegate respondsToSelector:@selector(photoBrowserDisplayCellDidLoadPhoto:)]) {
        [self.delegate photoBrowserDisplayCellDidLoadPhoto:self];
    }
    [self p_clearDownloadViews];
    //加载视频文件
    typeof(self) __weak weakSelf = self;

    [[TFPhotoHandler sharedHandler] getVideoAssetWithPHAsset:_photo resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
        if ([info[PHImageResultIsInCloudKey] boolValue]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf p_requestVideoFromICloud];
            });
        }
        else {
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf p_loadVideoWithAsset:asset];
                if ([weakSelf.delegate respondsToSelector:@selector(photoBrowserDisplayCellDidFinishLoadPhoto:)]) {
                    [weakSelf.delegate photoBrowserDisplayCellDidFinishLoadPhoto:weakSelf];
                }
            });
            
        }
    }];
}

- (void)p_loadVideoWithAsset:(AVAsset *)asset {
    if (![asset isEqual:self.videoPlayView.player.currentItem.asset]) {
        AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:asset];
        [self.videoPlayView.player replaceCurrentItemWithPlayerItem:item];
        
        //获取第一帧图片
        AVAssetImageGenerator *assetImageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
        assetImageGenerator.appliesPreferredTrackTransform = YES;
        assetImageGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
        
        CGImageRef thumbnailImageRef = NULL;
        CFTimeInterval thumbnailImageTime = 0.0;
        NSError *thumbnailImageGenerationError = nil;
        thumbnailImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 60)actualTime:NULL error:&thumbnailImageGenerationError];
        UIImage *thumbnailImage = thumbnailImageRef ? [[UIImage alloc]initWithCGImage: thumbnailImageRef] : nil;
        CGImageRelease(thumbnailImageRef);
        _photoScrollView.image = thumbnailImage;
        _photoScrollView.zoomImageView.frame = self.videoPlayView.playerLayer.videoRect;
    }
}

- (void)p_requestVideoFromICloud {
    typeof(self) __weak weakSelf = self;
    TFPhotoDownloadView *downloadView = [self p_showDownloadView];
    _iCloudRequestId = [[TFPhotoHandler sharedHandler] downLoadICloudVideoWithPHAsset:_photo progressHandler:^(double progress, NSError * _Nullable error, BOOL * _Nonnull stop, NSDictionary * _Nullable info) {
        if (!error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                downloadView.progress = progress;
            });
        }
    } resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
        //清空requestID
        weakSelf.iCloudRequestId = 0;
        dispatch_async(dispatch_get_main_queue(), ^{
            if (asset) {
                [weakSelf p_clearDownloadViews];
                //加载视频
                [weakSelf p_loadVideoWithAsset:asset];
                if ([weakSelf.delegate respondsToSelector:@selector(photoBrowserDisplayCellDidFinishLoadPhotoFromICloud:)]) {
                    [weakSelf.delegate photoBrowserDisplayCellDidFinishLoadPhotoFromICloud:weakSelf];
                }
            }
            else {
                [downloadView removeFromSuperview];
                [weakSelf p_showDownloadFailedView];
            }
        });
        
    }];
}

- (TFPhotoDownloadView *)p_showDownloadView {
    TFPhotoDownloadView *downloadView = [[TFPhotoDownloadView alloc] initWithFrame:CGRectMake(0.0, 0.0, 50.0, 50.0)];
    downloadView.progress = 0.0;
    downloadView.tag = kTFPhotoVideoDisplayDownloadProgressViewTag;
    downloadView.center = self.contentView.center;
    [self.contentView addSubview:downloadView];
    return downloadView;
}

- (void)p_showDownloadFailedView {
    //添加加载失败视图
    UIView *downloadFailView = [self p_photoDisplayCellDownloadFailView];
    [downloadFailView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(loadPhoto)]];
    downloadFailView.tag = kTFPhotoVideoDisplayDownloadFailViewTag;
    downloadFailView.frame = self.contentView.bounds;
    [self.contentView addSubview:downloadFailView];
}

- (UIView *)p_photoDisplayCellDownloadFailView {
    UIView *downloadFailView = [[UIView alloc] init];
    
    //添加subView
    UIImageView *failImageView = [[UIImageView alloc] initWithImage:[TFPhotoResourceHelper imageNamed:@"photo_download_fail"]];
    [downloadFailView addSubview:failImageView];
    
    UILabel *detailLabel = [[UILabel alloc] init];
    detailLabel.text = [TFPhotoResourceHelper localizedStringWithKey:@"视频加载失败，请点击重试"];
    detailLabel.textColor = [UIColor tfPhoto_hexColorWith:@"696969"];
    detailLabel.font = [UIFont systemFontOfSize:14];
    [downloadFailView addSubview:detailLabel];
    
    //添加约束
    failImageView.translatesAutoresizingMaskIntoConstraints = NO;
    detailLabel.translatesAutoresizingMaskIntoConstraints = NO;
    
    [NSLayoutConstraint constraintWithItem:failImageView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:downloadFailView attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0.0].active = YES;
    [NSLayoutConstraint constraintWithItem:failImageView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:downloadFailView attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:-30.0].active = YES;
    [NSLayoutConstraint constraintWithItem:detailLabel attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:downloadFailView attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0.0].active = YES;
    [NSLayoutConstraint constraintWithItem:detailLabel attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:failImageView attribute:NSLayoutAttributeBottom  multiplier:1.0 constant:6.0].active = YES;
    return downloadFailView;
}

- (void)p_clearDownloadViews {
    UIView *downloadFailView = [self.contentView viewWithTag:kTFPhotoVideoDisplayDownloadFailViewTag];
    if (downloadFailView) {
        [downloadFailView removeFromSuperview];
    }
    UIView *downloadProgressView = [self.contentView viewWithTag:kTFPhotoVideoDisplayDownloadProgressViewTag];
    if (downloadProgressView) {
        [downloadProgressView removeFromSuperview];
    }
}

- (void)clearPhoto {
    [self.videoPlayView resume];
    if (_iCloudRequestId!=0) {
        [[TFPhotoHandler sharedHandler] cancelICloudDownloadWith:_iCloudRequestId];
    }
}

- (void)dealloc {
    [self clearPhoto];
}

#pragma mark - lazy load.

- (TFPhotoScrollView *)photoScrollView {
    if (!_photoScrollView) {
        _photoScrollView = [[TFPhotoScrollView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        _photoScrollView.hidden = YES;
    }
    return _photoScrollView;
}

- (TFPhotoBrowserVideoPlayView *)videoPlayView {
    if (!_videoPlayView) {
        _videoPlayView = [[TFPhotoBrowserVideoPlayView alloc] initWithPlayer:[[AVPlayer alloc] init]];
    }
    return _videoPlayView;
}

@end
